// 导入axios
import axios from 'axios'
// 使用element-ui Message做消息提醒
import { Message } from 'element-ui';

const BASE_URL = "/api/"
let isRefreshing = true;
function checkStatus(response) {
  console.log(response)
  if (response && response.data.code === 401) {
    // 刷新token的函数,这需要添加一个开关，防止重复请求
    if (isRefreshing) {
      console.log(3)
      refreshTokenRequst()
    }
    isRefreshing = false;
    // 这个Promise函数很关键
    const retryOriginalRequest = new Promise((resolve) => {
      addSubscriber(() => {
        resolve(request(url, options))
      })
    });
    return retryOriginalRequest;
  } else {
    return response;
  }
}

function refreshTokenRequst() {
  let data;
  const refreshToken = localStorage.getItem('refreshToken');
  data = {
    refreshToken,
  }
  axios.request({
    baseURL: BASE_URL,
    url: '/user/refreshToken',
    method: 'POST',
    data,
  }).then((response) => {
    localStorage.setItem('refreshToken', response.data.refreshToken);
    localStorage.setItem('token', response.data.token);
    onAccessTokenFetched();
    isRefreshing = true;
  }).catch(error => console.log(error));
}

let subscribers = [];
function onAccessTokenFetched() {
  subscribers.forEach((callback) => {
    callback();
  })
  subscribers = [];
}

function addSubscriber(callback) {
  subscribers.push(callback)
}


export default function request(url, options) {
  console.log(url, options);
  const token = localStorage.getItem('token');
  const defaultOptions = {
    headers: {
      Authorization: `bearer${token}`,
    },
    withCredentials: true,
    url: url,
    baseURL: BASE_URL,
  };

  const newOptions = { ...options, ...defaultOptions };
  console.log(newOptions);
  return axios.request(newOptions)
    .then((res) => checkStatus(res))
    .catch(error => console.log(error));
}